package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //判断验证码输入是否正确
        String checkCode = request.getParameter("checkCode");

        //获取在session
        HttpSession session = request.getSession();
        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");

        // 删除session中的验证码, 确保验证码是一次性的
        session.removeAttribute("CHECKCODE_SERVER");

        //2.3 比较两码是否一致
        if (!checkCode.equalsIgnoreCase(checkcode_server)){
            request.setAttribute("msg","验证码错误");
            //请求转发到login。jsp页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        //获取用户输入信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //模拟判断效果
        if ("als".equals(username) && "123".equals(password)) {
            //将数据存入会话域对象中
            request.getSession().setAttribute("username", username);

            //---------记住用户名  start-------------
            //1. 获取是否勾选了"记住用户名"
            String rememberMe = request.getParameter("rememberMe");

            //2. 判断是否为 yes
            if ("yes".equals(rememberMe)){
                //勾选了的话就存到cookie里
                Cookie cookie = new Cookie("rememberMe",username);
                cookie.setMaxAge(10*60);
                response.addCookie(cookie);
            }
            //---------记住用户名  end-------------

            //重定向:浏览器的地址栏发生了改变,可以防止重复登录
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }
        //将错误的信息存到request域中,再转发到login.jsp中
        request.setAttribute("msg", "用户名或密码错误");
        request.getRequestDispatcher("/login.jsp").forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
